package com.micromsg.basic.web.controller;

import com.micromsg.basic.web.task.MyThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/thread")
public class ThreadController {
    // 127.0.0.1:9001/thread/t1

    @Qualifier("fixedThreadPool")
    @Autowired
    ThreadPoolExecutor fixedThreadPool;
    @Autowired
    ApplicationContext applicationContext;


    @RequestMapping(value = "/t1", method = RequestMethod.GET)
    public String t1() {
        int activeCount = fixedThreadPool.getActiveCount();
        int size = fixedThreadPool.getQueue().size();
        String format = String.format("activeCount = %s , QueueSize = %s", activeCount, size);
        return format;
    }

    @RequestMapping(value = "/t2", method = RequestMethod.GET)
    public String t2() {
        MyThread myThread = applicationContext.getBean(MyThread.class);
        int hashCode = myThread.hashCode();
        System.out.println(hashCode);
        fixedThreadPool.submit(myThread);
        int activeCount = fixedThreadPool.getActiveCount();
        return "" + activeCount;
    }

    @RequestMapping(value = "/ts", method = RequestMethod.GET)
    public void ts() {
//        fixedThreadPool.invokeAll()
//        fixedThreadPool.invokeAny()

        // 创建新线程来处理每个连接
        Thread thread = new Thread(() -> {
            try {
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread.start();

    }

}
